package com.supermap.dataservice.cloud.tracesource;

import com.alibaba.dubbo.config.annotation.Service;
import com.supermap.dataservice.mysql.config.DynamicDataSourceContextHolder;
import com.supermap.dataservice.util.JSONUtil;
import com.supermap.dubbo.api.cloud.tracesource.TraceSourceService;
import com.supermap.dubbo.api.cloud.tracesource.TraceaBility;
import com.supermap.dubbo.api.cloud.tracesource.TraceabilityAudit;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author aqua
 * @description 溯源实现类
 * @date 2018年12月21 上午 9:54
 * @email 1301584033@qq.com
 */
@Service
public class TraceSourceServiceImpl implements TraceSourceService {

    @Resource
    private TraceSourceMapper traceSourceMapper;

    @Override
    public Map<String,Object> getTraceSourceByFarmId(String beginTime,String endTime,String farmId) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        List<String> stringList =traceSourceMapper.getTop2Time(farmId);
        if(beginTime==null){
            if(stringList.size()>1){
                //2次收获
                beginTime=stringList.get(1);
            }else{
                //一次收获 第一次溯源
                beginTime=traceSourceMapper.getFarmCreaTime(farmId);
            }
        }
        if(endTime==null){
            if(stringList.size()>1){
                //2次收获
                endTime=stringList.get(0);
            }else{
                //一次收获 第一次溯源
                endTime=stringList.get(0);
            }
        }
        Map<String,Object> map =new HashMap<>();
        //获取农田基本信息
        TraceSoure traceSoureList=traceSourceMapper.getFarmAndFarmByFarmId(farmId);
        //获取生育期
         List<Puberty> pubertyList= traceSourceMapper.getPubertyByCodeId(traceSoureList.getCropId());
         List<Map<String,Object>> objectMap= traceSourceMapper.getPubertytTime(traceSoureList.getCropId(),farmId,beginTime,endTime);

        for(Puberty puberty:pubertyList){
            List<ObjectTlist> objectTlists=new ArrayList<>();
            //开始时间
           for(int i=0;i<objectMap.size();i++){
                   Integer index= (Integer) objectMap.get(i).get("indexid");
                   if(Integer.valueOf(puberty.getIndex())==index){
                       puberty.setBeginTime((String)objectMap.get(i).get("starttime"));
                   }

           }
            //结束时间
            for(int i=0;i<objectMap.size();i++){
                if(puberty.getBeginTime()!=null){
                      Integer index= (Integer) objectMap.get(i).get("indexid");
                      if(Integer.valueOf(puberty.getIndex())==index){
                          if(objectMap.size()-1==i){
                              puberty.setEndTime(endTime);
                          }else {
                              //时间要减一毫秒
                              String dateTime=(String) objectMap.get(i + 1).get("starttime");
                              dateTime=getTimeMinusOneSecond(dateTime);
                              puberty.setEndTime(dateTime);
                          }
                      }

                      }

                }
            if(puberty.getBeginTime()!=null&&puberty.getEndTime()!=null){
                    //咨询
                objectTlists.addAll(traceSourceMapper.getObjByFarmIdToAdv(farmId,puberty.getBeginTime(),puberty.getEndTime()));
                    //农情
                objectTlists.addAll(  traceSourceMapper.getObjByFarmIdToAgr(farmId,puberty.getBeginTime(),puberty.getEndTime()));
                    //灾情
                objectTlists.addAll( traceSourceMapper.getObjByFarmIdTodes(farmId,puberty.getBeginTime(),puberty.getEndTime()));
                    //农事
                objectTlists.addAll( traceSourceMapper.getObjByFarmIdToFarming(farmId,puberty.getBeginTime(),puberty.getEndTime()));
                    //建议
                objectTlists.addAll( traceSourceMapper.getObjByFarmIdToSugges(farmId,puberty.getBeginTime(),puberty.getEndTime()));
            }
            Collections.sort(objectTlists, new Comparator<ObjectTlist>() {
                @Override
                public int compare(ObjectTlist o1, ObjectTlist o2) {
                    return o2.getObjTime().compareTo(o1.getObjTime());
                }
            });
            puberty.setObjectTlists(objectTlists);

        }
        Collections.sort(pubertyList, new Comparator<Puberty>() {
            @Override
            public int compare(Puberty o1, Puberty o2) {
                return o2.getIndex().compareTo(o1.getIndex());
            }
        });
        traceSoureList.setPubertyList(pubertyList);
        map.put("code",200);
        map.put("msg","操作成功");
        map.put("beginTime",beginTime);
        map.put("endTime",endTime);
        map.put("data",traceSoureList);
        return map;
    }


    @Override
    public JSONUtil isNotHarvestByFarmId(String farmId) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        Integer count=traceSourceMapper.isNotHarvestByFarmId(farmId);
        return new JSONUtil().setCode(count>0?200:100).setMsg(count>0?"恭喜你，你可以溯源":"不能溯源请点击收获作物后再溯源");
    }

    @Override
    public JSONUtil insertTraceSource(TraceaBility traceaBility) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        String areaCode=traceSourceMapper.getFarmAreaCode(traceaBility.getFarm());
        DynamicDataSourceContextHolder.setDataSourceKey("ds1");
       String userId= traceSourceMapper.getSmsUserId(areaCode);
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        Integer count=traceSourceMapper.insertTraceSource(traceaBility);
       Integer id= traceSourceMapper.getInsertId();
        TraceabilityAudit traceabilityAudit = new TraceabilityAudit();
        traceabilityAudit.setUserid(userId);
        traceabilityAudit.setSuggest("创建待审核");
        traceabilityAudit.setTratid(id);
        traceabilityAudit.setStatue(0);
        //插入历史审核记录
        traceSourceMapper.insertTraceAudit(traceabilityAudit);
        return new JSONUtil().setMsg(userId).setCode(count>0?200:100).setCountSum(id).setData(traceSourceMapper.getFarmUserId(traceaBility.getFarm()));
    }

    @Override
    public JSONUtil getTraceSourceList(String farmId,String areaCode,Integer state,Integer userId) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        return new JSONUtil().setData(traceSourceMapper.getTraceSourceList(farmId,areaCode,state,userId));
    }

    @Override
    public JSONUtil getTop1TraceSourceList(String areaCode) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        return new JSONUtil().setData(traceSourceMapper.getTop1TraceSourceList(areaCode));
    }

    @Override
    public JSONUtil getFarmUserByFarmId(String farmId) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        return new JSONUtil().setData(traceSourceMapper.getFarmUserByFarmId(farmId));
    }

    @Override
    public JSONUtil getAllCropByFarmId(String farmId) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
       Integer code=  traceSourceMapper.getCropPardIdByFarmId(farmId);
        Map<String,Object> map= traceSourceMapper.getTopTime(code,farmId);
         if(map!=null){
             String starttime=(String)map.get("starttime");
             Integer indexid =(Integer)map.get("indexid");
             int count =traceSourceMapper.getTSTopTime(starttime,farmId);
             if(count==0){
                 return   new JSONUtil().setData(traceSourceMapper.getAllCropByFarmId(farmId,indexid));
             }
             return new JSONUtil().setData(traceSourceMapper.getAllCropByFarmId(farmId,0));
         }else{
             return   new JSONUtil().setData(traceSourceMapper.getAllCropByFarmId(farmId,0));
         }

    }




    @Override
    public JSONUtil getTraceAuth(String traceAuthId) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        Map<String,Object> map= traceSourceMapper.getTraceAuth(traceAuthId);
        DynamicDataSourceContextHolder.setDataSourceKey("ds1");
        String departName =traceSourceMapper.getDepartName((String)map.get("userid"));
        map.put("userName",departName);
        return new JSONUtil().setData(map);
    }

    @Override
    public JSONUtil putTraceAuth(TraceabilityAudit traceabilityAudit) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        traceSourceMapper.insertTraceAudit(traceabilityAudit);
        Integer id= traceSourceMapper.getInsertId();
        traceSourceMapper.updateTraceaBility(traceabilityAudit.getTratid(),traceabilityAudit.getStatue());
        return new JSONUtil().setMsg("操作成功!").setCountSum(id);
    }

    @Override
    public JSONUtil getUserAndFarmByFarmId(String farmId) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        return new JSONUtil().setData(traceSourceMapper.getUserAndFarmByFarmId(farmId));
    }

    @Override
    public JSONUtil getTraceSourceCropPubert(String beginTime, String endTime, String farmId) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        TraceSoure traceSoureList=traceSourceMapper.getFarmAndFarmByFarmId(farmId);
      //  List<Map<String,Object>> list=traceSourceMapper.getPubertyByFarmId(farmId);
        //获取生育期
        List<Puberty> pubertyList= traceSourceMapper.getPubertyByCodeId(traceSoureList.getCropId());
        List<Map<String,Object>> objectMap= traceSourceMapper.getPubertytTime(traceSoureList.getCropId(),farmId,beginTime,endTime);

        for(Puberty puberty:pubertyList) {
            List<ObjectTlist> objectTlists = new ArrayList<>();
            //开始时间
            for (int i = 0; i < objectMap.size(); i++) {
                Integer index = (Integer) objectMap.get(i).get("indexid");
                if (Integer.valueOf(puberty.getIndex()) == index) {
                    puberty.setBeginTime((String) objectMap.get(i).get("starttime"));
                }

            }
            //结束时间
            for (int i = 0; i < objectMap.size(); i++) {
                if (puberty.getBeginTime() != null) {
                    Integer index = (Integer) objectMap.get(i).get("indexid");
                    if (Integer.valueOf(puberty.getIndex()) == index) {
                        if (objectMap.size() - 1 == i) {
                            puberty.setEndTime(endTime);
                        } else {
                            //时间要减一毫秒
                            String dateTime = (String) objectMap.get(i + 1).get("starttime");
                            dateTime = getTimeMinusOneSecond(dateTime);
                            puberty.setEndTime(dateTime);
                        }
                    }

                }

            }
            //添加改生育期图片
            puberty.setImg(traceSourceMapper.getPubertyImg(farmId,puberty.getBeginTime(),puberty.getEndTime()));
        }
        return new JSONUtil().setData(pubertyList);
    }

    @Override
    public JSONUtil getTraceSourceCropPubertDetails(String beginTime, String endTime, String farmId) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        List<ObjectTlist> objectTlists=new ArrayList<>();
            //咨询
            objectTlists.addAll(traceSourceMapper.getObjByFarmIdToAdv(farmId,beginTime,endTime));
            //农情
            objectTlists.addAll(  traceSourceMapper.getObjByFarmIdToAgr(farmId,beginTime,endTime));
            //灾情
            objectTlists.addAll( traceSourceMapper.getObjByFarmIdTodes(farmId,beginTime,endTime));
            //农事
            objectTlists.addAll( traceSourceMapper.getObjByFarmIdToFarming(farmId,beginTime,endTime));
            //建议
            objectTlists.addAll( traceSourceMapper.getObjByFarmIdToSugges(farmId,beginTime,endTime));

        Collections.sort(objectTlists, new Comparator<ObjectTlist>() {
            @Override
            public int compare(ObjectTlist o1, ObjectTlist o2) {
                return o2.getObjTime().compareTo(o1.getObjTime());
            }
        });
        return new JSONUtil().setData(objectTlists);
    }

    @Override
    public JSONUtil getFarming(String farmId,String beginTime, String endTime,Integer type) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        return new JSONUtil().setData(traceSourceMapper.getFarming(farmId,beginTime,endTime,type));
    }

    @Override
    public JSONUtil getFarmDateTime(String farmId) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        String beginTime=null;
        String endTime=null;
        List<String> stringList =traceSourceMapper.getTop2Time(farmId);
        if(beginTime==null){
            if(stringList.size()>1){
                //2次收获
                beginTime=stringList.get(1);
            }else{
                //一次收获 第一次溯源
                beginTime=traceSourceMapper.getFarmCreaTime(farmId);
            }
        }
        if(endTime==null){
            if(stringList.size()>1){
                //2次收获
                endTime=stringList.get(0);
            }else{
                //一次收获 第一次溯源
                endTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            }
        }
        Map<String,String> dateTime=new HashMap<>();
        dateTime.put("beginTime",beginTime);
        dateTime.put("endTime",endTime);
        return  new JSONUtil().setData(dateTime);
    }

    @Override
    public Integer getBindUserId(String baseUserId) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds1");
        return traceSourceMapper.getBindUserId(baseUserId);
    }

    @Override
    public Integer getUserId(Integer traceId) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        return  traceSourceMapper.getUserIdByTraceId(traceId);
    }

    @Override
    public JSONUtil updateTrace(TraceaBility traceaBility) {

        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        TraceabilityAudit traceabilityAudit = traceSourceMapper.getTraceabilityAudit(traceaBility.getId());
        traceabilityAudit.setStatue(traceaBility.getState());
        traceSourceMapper.insertTraceAudit(traceabilityAudit);
        Integer id= traceSourceMapper.getInsertId();
        traceSourceMapper.updateTrace(traceaBility);
        String areaCode=traceSourceMapper.getFarmAreaCode(traceaBility.getFarm());
        DynamicDataSourceContextHolder.setDataSourceKey("ds1");
        String userId= traceSourceMapper.getSmsUserId(areaCode);
        return  new JSONUtil().setData(traceSourceMapper.getFarmUserId(traceaBility.getFarm())).setMsg(userId);
    }

    @Override
    public String getBaseUserId(String bindUserId) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds1");
        return traceSourceMapper.getBaseUserId(bindUserId);
    }

    public String getTimeMinusOneSecond(String dateTime) {
       SimpleDateFormat sdf=  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       Date date = null;
       try {
           date = sdf.parse(dateTime);
       } catch (ParseException e) {
           e.printStackTrace();
       }
       Calendar calendar = Calendar.getInstance();
       calendar.setTime(date);
       calendar.add(Calendar.SECOND, -1);
        return  sdf.format(calendar.getTime());
   }

}
